package com.rendevous.dao;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.ParseException;

import com.rendevous.bean.Task;
import com.rendevous.utils.Constants;
import com.rendevous.utils.JSONParser;

public class FileDAO extends BasicDAO {
	protected JSONObject JSONtask;

	public FileDAO(String filePath) throws IOException, ParseException {
		super();
		this.filePath = filePath;
		File textFile = new File(filePath);;
		Reader fileReader = new FileReader(textFile);
		JSONArray taskList = (JSONArray) parser.parse(fileReader);
		this.taskMap = parser.JSONArray2Map(taskList);
	}

	public boolean createTask(JSONObject task) {
		if (task.isEmpty()) {
			return false;
		} else {
			taskMap.put((Long) task.get(Constants.KEY_ID), task);
			return updateFile();
		}
	}

	public boolean updateTask(JSONObject task) {
		taskMap.put((Long)task.get(Constants.KEY_ID), task);
		return updateFile();
	}

	@Override
	public boolean createTask(Task task) {
		JSONtask = parser.Task2Json(task);
		return createTask(JSONtask);
	}

	@Override
	public boolean updateTask(Task task) {
		JSONtask = parser.Task2Json(task);
		return updateTask(JSONtask);
	}

	@Override
	public boolean deleteTask(long id) {
		taskMap.remove(id);
		return updateFile();
	}

	@Override
	public boolean updateFile() {
		JSONArray taskList = new JSONArray();
		taskList.addAll(taskMap.values());
		try {
			File data = new File(Constants.DATA_PATH);
			Writer fileWriter = new FileWriter(data);
			BufferedWriter out = new BufferedWriter(fileWriter);
			out.write(taskList.toString());
			out.close();
			return true;
		} catch (Exception e) {
			System.err.println(Constants.ERROR_MSG);
			return false;
		}
	}

}
